package 线程同步;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/*
* 虽然我们可以理解同步代码块和同步方法的锁对象问题，但是我们并没有直接看到在哪里加上了锁，在哪里释放了锁，
* 为了更清晰的表达如何加锁和释放锁，JDK5以后提供了一个新的锁对象Lock
* Lock是接口不能直接实例化，这里采用它的实现类ReentrantLock来实例化
 * */
public class Lock锁 {
    public static void main(String[] args) {
        SellTicket4 st4 = new SellTicket4();
        Thread t1 = new Thread(st4, "窗口1");
        Thread t2 = new Thread(st4, "窗口2");
        Thread t3 = new Thread(st4, "窗口3");
        t1.start();
        t2.start();
        t3.start();
    }
}
class SellTicket4 implements Runnable{
    private int tickets=100;
    private Lock lock=new ReentrantLock();
    @Override
    public void run() {
        while (true){
            try {
                lock.lock();/*上锁*/
                if(tickets>0){
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName()+"正在出售第"+tickets+"张票");
                    tickets--;
                }
            } finally {
                lock.unlock();/*解锁*/
            }
        }
    }
}